/**
 * 用户管理
 */
const router = require('koa-router')()
const User = require('../models/userSchema')
const Role = require('../models/roleSchema')
const Dept = require('../models/deptSchema');
const Leave = require('../models/leaveSchema')
const util = require('../utils/util')
const jwt = require('jsonwebtoken')
const log4js = require('../utils/log4j')
const md5 = require('md5')
const moment = require('moment');

router.prefix('/leave')

router.get('/count', async ctx => {
  ctx.body = util.success(0)
})

router.get('/list', async (ctx) => {
  const { applyState, pageNum, pageSize, type } = ctx.request.query;
  const auth = ctx.request.header.authorization;  
  const { data } = util.decoded(auth);

  const { page, skipIndex } = util.pager({ pageNum, pageSize });
  try {
    let params = {}
    if (type === 'approve') {
      if ([1, 2].includes(parseInt(applyState))) {
        params.curAuditUserName = data.userName;
        params.applyState = {$in: [1, 2]}
      } else if (applyState > 2) {
        params = { "auditFlows.userName": data.userName, applyState: parseInt(applyState) }
      } else {
        params = { "auditFlows.userName": data.userName, }
      }
    } else {
      params = {
        'applyUser.userName': data.userName,
      } 
      if (applyState) params.applyState = applyState;
    }
    console.log('params: ', params);
    const query = Leave.find(params);
    const list = await query.skip(skipIndex).limit(pageSize);
    const total = await Leave.countDocuments(params);
    ctx.body = util.success({
      list, 
      page: {
       ...page,
        total
      }
    })
  } catch (error) {
    ctx.body = util.fail(`查询失败 ${error.stack}`)
  }
})

router.post('/operate', async (ctx) => {
  const { action, _id, ...params } = ctx.request.body;
  try {
    const auth = ctx.request.header.authorization;  
    const { data } = util.decoded(auth);

    let msg = '';
    let res = {};
    if (action === 'delete') {
      // 删除
      await Leave.findByIdAndUpdate(_id, { applyState: 5 });
      msg = '删除成功';
    } else if (_id && action === 'pass') { 
      let log = {
        time: new Date(),
        userName: data.userName,
        action
      }
      // 审核: 通过 / 下一个人
      let leaveItem = await Leave.findById(_id);
      let index = leaveItem.auditFlows.findIndex((item) => item.userName === leaveItem.curAuditUserName);
      let curAuditUserName = '';
      let applyState = leaveItem.applyState;
      let auditLogs = [...leaveItem.auditLogs];
      // 1. 移交给下一个人
      if (index !== leaveItem.auditFlows.length - 1) {
        curAuditUserName = leaveItem.auditFlows[index + 1].userName;
        applyState = 2;
      } else {
        // 2. 已经是最后一个人了, 那么就改变状态为 applyState: 4
        curAuditUserName = leaveItem.auditFlows[
          leaveItem.auditFlows.length - 1
        ].userName;
        applyState = 4;
      }
      auditLogs.push(log);
      res = await Leave.findByIdAndUpdate(_id, { curAuditUserName, auditLogs, applyState });
    } else if (_id && action === 'reject') { 
      let log = {
        time: new Date(),
        userName: data.userName,
        action
      }
      let leaveItem = await Leave.findById(_id);
      let auditLogs = [...leaveItem.auditLogs, log];
      // 审核: 驳回
      res = await Leave.findByIdAndUpdate(_id, { 
        curAuditUserName: data.userName, 
        auditLogs, 
        applyState: 5 
      });
    } else {
      // 新增 休假
      const total = await Leave.countDocuments();
      params.orderNo = `XJ${moment().format('YYYYMMDD')}${total}`

      // 上级部门 id
      let dept = await Dept.findById(data.deptId.pop());
      // 人事 和 财务 的负责人信息
      let userList = await Dept.find({ deptName: { $in: ['人事部门', '财务部门'] } });

      let auditUsers = dept.userName
      let auditFlows = [
        {userId: dept._id, userName: dept.userName, userEmail: dept.userEmail}
      ]
      userList.map(user => {
        auditFlows.push(
          {userId: user._id, userName: user.userName, userEmail: user.userEmail}
        )
        auditUsers += `, ${user.userName}`
      })
      params.auditUsers = auditUsers
      params.curAuditUserName = dept.userName
      params.auditFlows = auditFlows
      params.auditLogs = []
      params.applyUser = {
        userId: data._id,
        userName: data.userName,
        userEmail: data.userEmail,
      }
      res = await Leave.create(params)
    }

    ctx.body = util.success(res, msg);
    return;
  } catch (error) {
    ctx.body = util.fail(`操作失败 ${error.stack}`)
  }
})

module.exports = router
